package com.cn.steam.iam.controller.open;

import com.cn.steam.foundation.common.model.exception.BadRequestException;
import com.cn.steam.foundation.common.web.config.jwt.ServiceContextHolder;
import com.cn.steam.iam.model.po.IamRole;
import com.cn.steam.iam.service.IamRoleProfileService;
import com.cn.steam.iam.service.IamRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

import static com.cn.steam.foundation.common.model.CommonConstant.OPEN_ROLE_V1_API;

/**
 * @author zjm
 * @date 2021/05/07
 */
@RestController
@RequestMapping(OPEN_ROLE_V1_API)
public class IamRoleController {

    @Autowired
    private IamRoleProfileService iamRoleProfileService;

    @Autowired
    private IamRoleService iamRoleService;


    @PreAuthorize("hasAuthority('ROLE_ADD')")
    @PostMapping("/add")
    public IamRole add(@Valid @RequestBody IamRole iamRole){
        if(!ServiceContextHolder.getOrInitServiceContext().isAdmin()){
            throw new BadRequestException("the account has no permission.");
        }
        String roleId =iamRoleProfileService.addIamRoleMapping(iamRole);
        iamRole.setRoleId(roleId);
        return iamRole;
    }

    @PreAuthorize("hasAuthority('ROLE_UPDATE')")
    @PutMapping("/update")
    public IamRole update(@Valid @RequestBody IamRole iamRole){
        if(!ServiceContextHolder.getOrInitServiceContext().isAdmin()){
            throw new BadRequestException("the account has no permission.");
        }
        iamRoleProfileService.updateById(iamRole);
        return iamRole;
    }

    @PreAuthorize("hasAuthority('ROLE_DELETE')")
    @DeleteMapping("/delete/{roleId}")
    public IamRole delete(@PathVariable String roleId){
        if(!ServiceContextHolder.getOrInitServiceContext().isAdmin()){
            throw new BadRequestException("the account has no permission.");
        }
        IamRole iamRole = iamRoleProfileService.getById(roleId);
        if(iamRole == null){
            throw new BadRequestException("the role does not exist.");
        }
        iamRoleService.deleteRole(iamRole.getRoleId());
        return iamRole;
    }

//    @PreAuthorize("hasAuthority('ROLE_QUERY')")
//    @GetMapping("/query/list")
//    public List<IamRole> queryList(IamRoleVo iamRoleVo){
//        if(!ServiceContextHolder.getOrInitServiceContext().isAdmin()){
//            throw new BadRequestException("the account has no permission.");
//        }
//
//        if (null != iamRoleVo.getPageNo() && null != iamRoleVo.getPageSize()) {
//            PageHelper.startPage(iamRoleVo.getPageNo(), iamRoleVo.getPageSize());
//        }
//        List<IamRole> iamRoleList = iamRoleProfileService.qryIamRoleList(iamRoleVo);
//        return iamRoleList;
//    }
}
